import React, { memo, useEffect, useRef ,useState,useCallback} from 'react'
import { shallowEqual, useDispatch, useSelector } from 'react-redux'
import { useNavigate } from 'react-router'
import { Slider } from 'antd'

import {
  PlayerWrapper,
  Control,
  PlayInfo,
  Operator
} from './style'
import { formatTime, getSongUrl } from '@/utils/format'
import PlaySonglist from '../play-songlist'
import {
  changeCurrentSongAction,
  getCurrentSongLyricIndexAction,
  changeHowPlayAction
} from '../../store/actionCreators'


export default memo(function Player(props) {
  const audioRef = useRef()
  const [isPlay, setIsPlay] = useState(false)
  const [currentTime, setCurrentTime] = useState(0)
  const [progress, setProgress] = useState(0)
  const [isChange, setIsChange] = useState(false)
  const [isShowList, setIsShowList] = useState(false)
  const { currentSongDetail ,songList , songLyric,currentSongLyricIndex,howPlay} = useSelector(state => ({
    currentSongDetail: state.getIn(['player', 'currentSongDetail']),
    songList: state.getIn(['player', 'songList']),
    songLyric: state.getIn(['player', 'songLyric']),
    currentSongLyricIndex: state.getIn(['player', 'currentSongLyricIndex']),
    howPlay:state.getIn(['player','howPlay'])
  }), shallowEqual)
  useEffect(() => {
    audioRef.current.src = getSongUrl(currentSongDetail.id)
    audioRef.current.play().then(res => {
      setIsPlay(true)
    }).catch(err => {
      setIsPlay(false)
    })
  },[audioRef,currentSongDetail])
  const playMusic = () => {
    setIsPlay(!isPlay)
    if (isPlay) {
      audioRef.current.pause()
    } else {
      audioRef.current.play()
    }
  }
  const timeChange = (e) => {
    if (!isChange) {
      const currentTime = e.target.currentTime * 1000
      setCurrentTime(currentTime)
      const progress = currentTime / currentSongDetail.dt * 100
      setProgress(progress)
    }

    let lrcLength = songLyric.length;
    let i = 0;
    for (; i < lrcLength; i++) {
      const lrcTime = songLyric[i].totalTime;
      if (currentTime  < lrcTime) {
        break
      }
    }
    const finalIndex = i - 1;
    if (finalIndex !== currentSongLyricIndex) {
      dispatch(getCurrentSongLyricIndexAction(finalIndex));
    }
   
  }
  const sliderChange = useCallback((e) => {
    setProgress(e)
    const currentTime = e / 100 * currentSongDetail.dt
    setCurrentTime(currentTime)
    setIsChange(true)
  },[currentSongDetail])
  const sliderAfterChange = useCallback((e) => {
    const currentTime = e / 100 * currentSongDetail.dt / 1000
    console.log(currentTime);
    audioRef.current.currentTime = currentTime
    setIsChange(false)
  }, [currentSongDetail])
  const dispatch = useDispatch()
  const nextMusic = (tag) => {
    dispatch(changeCurrentSongAction(tag))
  }
  const changeIsShow = () => {
    setIsShowList(!isShowList)
  }
  const changeHowPlay = () => {
    dispatch(changeHowPlayAction((howPlay + 1) % 3))
  }
  const navigator = useNavigate()
  const goToSong = (id) => {
   
    navigator(`/discover/song/${id}`)
  }
  return (
    <PlayerWrapper className="sprite_playbar">
      <div className="content wrap-v2">
      <Control isPlay={isPlay}>
        <button className="sprite_playbar btn prev" onClick={e => nextMusic(-1)}></button>
        <button className="sprite_playbar btn play" onClick={e => playMusic()}></button>
        <button className="sprite_playbar btn next" onClick={e => nextMusic(1)}></button>
      </Control>
      <PlayInfo>
        <div className="image" onClick={e => goToSong(currentSongDetail.id)}>
          <img src={currentSongDetail.al.picUrl} alt="" />
        </div>
        <div className="info">
          <div className="song">
              <span className="song-name">{currentSongDetail.name}</span>
              <span className="singer-name">{ currentSongDetail.ar[0].name}</span>
          </div>
          <div className="progress">
              <Slider value={progress} onChange={sliderChange} onAfterChange={ sliderAfterChange}/>
            <div className="time">
              <span className="now-time">{formatTime(currentTime,'mm:ss')}</span>
              <span className="divider">/</span>
              <span className="total-time">{ formatTime(currentSongDetail.dt,'mm:ss') }</span>
            </div>
          </div>
        </div>
        </PlayInfo>
        <Operator howPlay={howPlay}>
          <div className="left">
            <button className="sprite_playbar btn favor"></button>
            <button className="sprite_playbar btn share"></button>
          </div>
          <div className="right sprite_playbar">
            <button className="sprite_playbar btn volume"></button>
            <button className="sprite_playbar btn loop" onClick={e => changeHowPlay()}></button>
            <button className="sprite_playbar btn playlist" onClick={e => changeIsShow()}>
              {songList.length}
            </button>
          </div>
        </Operator>
      </div>
      {
        isShowList ? <PlaySonglist changeIsShow={e => changeIsShow()}/> : null 
      }
      <audio ref={audioRef} onTimeUpdate={e => timeChange(e)} onEnded={e => nextMusic(1)}> </audio>
    </PlayerWrapper>
  )
})
